package net.huashitong.Project.web;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import net.huashitong.Project.entity.*;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.service.*;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.service.NodeNewtempletService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.MessageFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.MessageService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sirdc.modules.bnp.service.SysNodeScheduleService;
import com.sirdc.modules.bnp.service.SysNodeTempleteService;
import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;

import net.huashitong.Project.filter.NoticeFilter;
import net.huashitong.Project.filter.ProjectFilter;
import net.huashitong.node.entity.NodeSchedules;
import net.huashitong.node.entity.NodeTemplet;
import net.huashitong.node.service.NodeSchedulesService;
import net.huashitong.node.utile.DateUtil;

import static net.huashitong.Project.util.HolidayUtils.calLeaveDays;

@Controller
@RequestMapping(value = "/api/project")
public class ProjectController extends JsonBaseController {

    private final static String apiKey = "b3232c91e3336d52ae80b73bb0a1cb912";       //关闭
//    private final static String apiKey = "b3232c91e3336d52ae80b73bb0a1cb91";

    @Autowired
    private NodeSchedulesService nodeScheService;
    @Autowired
    private SysNodeTempleteService templeteService;
    @Autowired
    private SysNodeScheduleService scheduleService;
    @Autowired
    private ProIndustryTypeService proIndusService;
    @Autowired
    private ProImageService proImgService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private NodeFileService nodeFileService;
    @Autowired
    private FilesService filesService;
    @Autowired
    private NodeLogService logService;

    @Autowired
    private VersionService versionService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private NewProjectsService projectService;
    @Autowired
    private NodeNewtempletService nodeNewtempletService;

    @Override
    protected String getView(String view) {
        return null;
    }


    public static void main(String[] args) {
        System.out.println("2017.04.15".compareTo(DateUtil.addDays("2017.04.01", Integer.parseInt("20") - 1)));
        System.out.println(DateUtil.addDays("2017.04.01", Integer.parseInt("20") - 1));
    }

    @ResponseBody
    @RequestMapping(value = "fileterNode")
    public Message filterNode(HttpServletRequest request) {
        String projectId = request.getParameter("projectId");
        String type = request.getParameter("type");
        List<NodeSchedules> list = nodeScheService.queryNodeSchedulesByProId(projectId);
        List<NodeSchedules> leadNodes = new ArrayList<NodeSchedules>();
        List<NodeSchedules> normalNodes = new ArrayList<NodeSchedules>();
        List<NodeSchedules> delayNodes = new ArrayList<NodeSchedules>();
        for (NodeSchedules schedules : list) {
            if (!"0".equals(schedules.getPlanTime())) {
                if (!"1".equals(schedules.getType())) {
                    if ("0".equals(schedules.getStatus())) {
                        int zxz = DateUtil.getDate().compareTo(DateUtil.addDays(schedules.getFactBeginDate(), Integer.parseInt(schedules.getPlanTime())));
                        if (zxz > 0) {
                            schedules.setStatus("1");
                            delayNodes.add(schedules);
                        } else {
                            schedules.setStatus("0");
                            normalNodes.add(schedules);
                        }
                    } else if ("-1".equals(schedules.getStatus())) {
                        schedules.setStatus("2");
                        normalNodes.add(schedules);
                    } else if ("1".equals(schedules.getStatus())) {
                        System.out.println("NodeId=" + schedules.getNodeId());
                        int wc = schedules.getFactFinishDate().compareTo(DateUtil.addDays(schedules.getFactBeginDate(), Integer.parseInt(schedules.getPlanTime()) - 1));
                        if (wc < 0) {
                            schedules.setStatus("-1");
                            leadNodes.add(schedules);
                        } else if (wc == 0) {
                            schedules.setStatus("0");
                            normalNodes.add(schedules);
                        } else if (wc > 0) {
                            schedules.setStatus("1");
                            delayNodes.add(schedules);
                        }
                    }
                }

            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if ("-1".equals(type)) {
            map.put("nodeList", leadNodes);
        } else if ("0".equals(type)) {
            map.put("nodeList", normalNodes);
        } else if ("1".equals(type)) {
            map.put("nodeList", delayNodes);
        } else {
            map.put("nodeList", new ArrayList<Map<String, Object>>());
        }
        return coverMessage("200", "获取成功", map);
    }

    @ResponseBody
    @RequestMapping(value = "flowChart")
    public Message flowChart(@RequestParam String projectId) {
        ProjectImages proImages = proImgService.query(projectId);
        Map<String, Object> map = new HashMap<String, Object>();
        if (proImages != null) {
            map.put("flowChartUrl", proImages.getImgUrl());//流程图url
            return coverMessage("200", "获取成功", map);
        } else {
            return coverMessage("500", "项目流程图不存在");
        }

    }

    @ResponseBody
    @RequestMapping(value = "/nodeDetail")
    public Message getNodeDetail(HttpServletRequest request) {
        String nodeId = request.getParameter("nodeId");
        String projectId = request.getParameter("projectId");
        Map<String, Object> map = new HashMap<String, Object>();
        NodeSchedules schedules = scheduleService.getNodeSchedules(projectId, nodeId);
        map.put("nodeName", schedules.getNodeName());//节点名称
        map.put("planTime", StringUtils.isNotEmpty(schedules.getPlanTime()) ? schedules.getPlanTime() : "暂无");//计划用时
        map.put("resDept", schedules.getResDept());//责任单位
        map.put("restUser", StringUtils.isNotEmpty(schedules.getResUser()) ? schedules.getResUser() : "无");//责任人
        map.put("operatorUser", StringUtils.isNotEmpty(schedules.getOperatorUser()) ? schedules.getOperatorUser() : "无");//经办人
        map.put("operatorPhone", StringUtils.isNotEmpty(schedules.getOperatorPhone()) ? schedules.getOperatorPhone() : "无");//经办人电话
        map.put("pactTime", StringUtils.isNotEmpty(schedules.getFactTime()) ? schedules.getFactTime() : "暂无");//实际用时
        map.put("restUserPhone", schedules.getResUserPhone());
        map.put("planFinishDate", StringUtils.isNotEmpty(schedules.getPlanFinishDate()) ? schedules.getPlanFinishDate() : "暂无");//实际完成时间
        map.put("planBeginDate", StringUtils.isNotEmpty(schedules.getPlanBeginDate()) ? schedules.getPlanBeginDate() : "暂无");//计划完成时间
        map.put("factBeginDate", StringUtils.isNotEmpty(schedules.getFactBeginDate()) ? schedules.getFactBeginDate() : "暂无");
        map.put("factFinishDate", StringUtils.isNotEmpty(schedules.getFactFinishDate()) ? schedules.getFactFinishDate() : "暂无");
        return coverMessage("200", "获取成功", map);
    }


    @ResponseBody
    @RequestMapping(value = "getUsersByDept")
    public Message setResUserAndPlanTime(@RequestParam String resDept, @RequestParam String type) {
        List<SysDept> depts = sysDeptService.query();
        SysDept dept = new SysDept();
        int flag = 0;
        for (SysDept deptdemo : depts) {
            if (resDept.indexOf("、") == -1) {
                if (resDept.equals(deptdemo.getDeptName())) {
                    dept = deptdemo;
                    flag = 1;
                    break;
                }
            }
        }
        if (flag == 1) {
            List<Map<String, Object>> userMaps = new ArrayList<Map<String, Object>>();
            SysUserFilter filter = new SysUserFilter();
            List<SysUserDataBean> userBeans = sysUserService.queryOnDatabean(filter);
            for (SysUserDataBean user : userBeans) {
                if (user.getDeptId().equals(dept.getSysId()) && user.getPosition().equals(type)) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("mobile", user.getUsername());
                    map.put("name", user.getName());
                    map.put("userId", user.getSysId());
                    userMaps.add(map);
                }
            }
            if (userMaps.isEmpty()) {
                return coverMessage("500", "该部门没有成员，请在后台添加");
            } else {
                return coverMessage("200", "获取成功", userMaps);
            }
        } else {
            return coverMessage("500", "该部门没有成员，请在后台添加");
        }
    }

    @ResponseBody
    @RequestMapping(value = "setNodeInfo")
    public Message setNodeInfo(HttpServletRequest request) {
        try {
            SysUserDataBean user = new SysUserDataBean();
            SysUserDataBean operatoruser = new SysUserDataBean();
            String userId = request.getParameter("userId");
            String operatorId = request.getParameter("operator");
            String planTime = request.getParameter("planTime");
            String projectId = request.getParameter("projectId");
            String nodeId = request.getParameter("nodeId");
            String reset = request.getParameter("reset");
            NodeSchedules nodeSchedule = nodeScheService.getNOdeSchedule(projectId, nodeId);
            if (!"0".equals(reset)) {
                int x = 0;
                if (!"undefined".equals(userId) || !"".equals(userId)) {
                    user = sysUserService.getUserDataBeanById(userId);
                    nodeSchedule.setResUser(user.getName());
                    nodeSchedule.setResUserPhone(user.getUsername());
                    nodeSchedule.setResUserId(userId);
                    x = 1;
                }
                if (!"undefined".equals(operatorId) || !"".equals(operatorId)) {
                    operatoruser = sysUserService.getUserDataBeanById(operatorId);
                    nodeSchedule.setOperatorUser(operatoruser.getName());
                    nodeSchedule.setOperatorPhone(operatoruser.getUsername());
                    nodeSchedule.setOperatorUserId(operatorId);
                    x = 1;
                }

                if (x == 1) {
                    nodeSchedule.setPlanTime(planTime);
                }


            } else {
                nodeSchedule.setResUser("");
                nodeSchedule.setResUserPhone("");
                nodeSchedule.setResUserId("");
                nodeSchedule.setOperatorUser("");
                nodeSchedule.setOperatorPhone("");
                nodeSchedule.setOperatorUserId("");
                nodeSchedule.setPlanTime("0");

            }
            nodeScheService.update(nodeSchedule);
            NodeSchedules bigNode = nodeScheService.getNOdeSchedule(nodeSchedule.getProjectId(), nodeSchedule.getNodeId().split("\\.")[0]);
            List<NodeSchedules> list = nodeScheService.queryNodeSchedulesByProId(nodeSchedule.getProjectId());
            int sumPlanTime = 0;
            for (NodeSchedules node : list) {
                if ("2".equals(node.getType()) && bigNode.getNodeId().equals(node.getNodeId().split("\\.")[0])) {
                    if (StringUtils.isNotEmpty(node.getPlanTime())) {
                        sumPlanTime += Integer.parseInt(node.getPlanTime());
                    }
                }
            }
            System.out.println(sumPlanTime);
            bigNode.setPlanTime(sumPlanTime + "");
            nodeScheService.update(bigNode);

            /*
             * 处理大节点时间问题
             */
        } catch (Exception e) {
            return coverMessage("500", "设置失败");
        }
        return coverMessage("200", "设置成功");
    }



    /**
     * 待办任务详情接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "myNodeDetail")
    public Message myNodeDetail(HttpServletRequest request) {
        String projectId = request.getParameter("projectId");
        String nodeId = request.getParameter("nodeId");
        NodeSchedules node = nodeScheService.getNOdeSchedule(projectId, nodeId);
        NodeSchedules parentNode = nodeScheService.getNOdeSchedule(projectId, node.getNodeId().split("\\.")[0]);
        System.out.println("111=" + node.getNodeId().split("\\.")[0]);
        List<NodeSchedules> childNodeList = nodeScheService.getChlidNodes(projectId, parentNode.getNodeId() + ".");
        System.out.println("222=" + parentNode.getNodeId() + ".");
        int n = Integer.parseInt(node.getNodeId().split("\\.")[1]);
        System.out.println("333=" + node.getNodeId().split("\\.")[1]);
        List<NodeSchedules> upNodeList = new ArrayList<NodeSchedules>();
        int flag = 0;
        for (int i = n - 1; i >= 1; i--) {
            for (NodeSchedules nodeSchedules : childNodeList) {
                if (StringUtils.isNotEmpty(nodeSchedules.getPlanTime()) && (i + "").equals(nodeSchedules.getNodeId().split("\\.")[1])) {
                    upNodeList.add(nodeSchedules);
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                break;
            }
        }
        if (flag == 0) {
            String nodeIdStr = parentNode.getPreNodeId();
            String[] nodeIds = nodeIdStr.split(",");

            upNodeList = nodeScheService.getNodesByIds(nodeIds, projectId);
        }
        //List<NodeFile> nodeFiles = nodeFileService.getFilesByNodeId(parentNode.getNodeId());
        List<Files> nodeFiles = filesService.queryByAcceptId(projectId, nodeId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("upNodeList", upNodeList);
        map.put("nodeFiles", nodeFiles);
        return coverMessage("200", "获取成功", map);
    }

    /**
     * 发件清单接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendFilesList")
    public Message sendFilesList(HttpServletRequest request) {
        List<Files> files = new ArrayList<Files>();
        String projectId = request.getParameter("projectId");
        String nodeId = request.getParameter("nodeId");
        NodeSchedules node = nodeScheService.getNOdeSchedule(projectId, nodeId);
        NodeSchedules nextNode = new NodeSchedules();
        List<NodeSchedules> allNodes = nodeScheService.queryNodeSchedulesByProId(projectId);
        int flag = 0;
        for (NodeSchedules nSchedules : allNodes) {
            String[] nodeids = nSchedules.getPreNodeId().split(",");
            for (int i = 0; i < nodeids.length; i++) {
                if (nodeids[i].equals(node.getNodeId().split("\\.")[0])) {
                    nextNode = nSchedules;
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                break;
            }
        }
        System.out.println(nextNode.getNodeId());
//		List<NodeFile> files = nodeFileService.getFilesByNodeId(nextNode.getNodeId());
        files = filesService.query(projectId, nextNode.getNodeId());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fileList", files);
        return coverMessage("200", "获取成功", map);
    }

    //预警项目接口
    @ResponseBody
    @RequestMapping(value = "warning")
    public Message warning() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> proMap1 = new HashMap<>();
        proMap1.put("title", "永泰县妇幼保健院迁建项目已延期25天");
        list.add(proMap1);
        Map<String, Object> proMap2 = new HashMap<>();
        proMap2.put("title", "福州市保罗环保产业示范基地已延期2天");
        list.add(proMap2);
        map.put("warningList", list);
        return coverMessage("200", "获取成功", map);
    }

    @ResponseBody
    @RequestMapping(value = "lookFile")
    public Message lookFile(HttpServletRequest request) {
        String fileId = request.getParameter("fileId");
        Files file = filesService.getByLockId(fileId);
        Map<String, Object> map = new HashMap<>();
        map.put("fileId", file.getSysId());
        if (StringUtils.isNotEmpty(file.getFilePath())) {
            map.put("fileUrl", file.getFilePath());
            return coverMessage("200", "获取成功", map);
        } else {
            return coverMessage("500", "获取成功", map);
        }
    }

    /**
     * 接收文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "acceptFile")
    public Message acceptFile(HttpServletRequest request) {
        String fileId = request.getParameter("fileId");
        Files file = filesService.getByLockId(fileId);
        file.setStatus("2");
        filesService.update(file);
        NodeSchedules node = nodeScheService.getNOdeSchedule(file.getProjectId(), file.getNodeId());
        NodeLog log = new NodeLog();
        log.setProjectId(file.getProjectId());
        log.setNodeId(file.getNodeId());
        log.setTime("接收时间：" + DateUtil.getDateByYMD());
        log.setUsername("接收人：" + node.getResUser());
        logService.save(log);
        return coverMessage("200", "查收成功");
    }


    /**
     * 办结文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "endFile")
    public Message endFile(HttpServletRequest request) {
        String fileId = request.getParameter("fileId");
        Files file = filesService.getByLockId(fileId);
        file.setStatus("4");
        filesService.update(file);
        NodeSchedules node = nodeScheService.getNOdeSchedule(file.getProjectId(), file.getNodeId());
        NodeLog log = new NodeLog();
        log.setTime("办结时间：" + DateUtil.getDateByYMD());
        log.setUsername("办结人：" + node.getResUser());
        logService.save(log);
        return coverMessage("200", "办结成功");
    }

    /**
     * 办结所有文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "endAllFile")
    public Message endAllFile(HttpServletRequest request) {
        String nodeId = request.getParameter("nodeId");
        String projectId = request.getParameter("projectId");
        NodeSchedules parentNode = nodeScheService.getNOdeSchedule(projectId, nodeId.split("\\.")[0]);
        List<Files> list = filesService.query(projectId, parentNode.getNodeId());
        for (Files file : list) {
            file.setStatus("4");
            if (!StringUtils.isNotEmpty(file.getFilePath())) {
                file.setStatus("5");
            }
            filesService.update(file);
        }
        return coverMessage("200", "已全部办结");
    }

    // 流转化成字符串
    public static String inputStream2String(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }

    //流转化成文件  
    public static void inputStream2File(InputStream is, String savePath) throws Exception {
        System.out.println("文件保存路径为:" + savePath);
        File file = new File(savePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        file.createNewFile();
        InputStream inputSteam = is;
        BufferedInputStream fis = new BufferedInputStream(inputSteam);
        FileOutputStream fos = new FileOutputStream(file);
        int f;
        while ((f = fis.read()) != -1) {
            fos.write(f);
        }
        fos.flush();
        fos.close();
        fis.close();
        inputSteam.close();
    }

    /**
     * 查询行业分类列表接口
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryProjectIndustryType")
    public Message queryProjectIndustryType() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<ProIndustryType> industryTypes = proIndusService.query();
        for (ProIndustryType type : industryTypes) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("typeName", type.getTypeName());
            map.put("typeCode", type.getTypeCode());
            list.add(map);
        }
        return coverMessage("200", "获取成功", list);
    }

    /**
     * 查询用户信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryUserMessage")
    public Message queryUserMessage(@RequestBody MessageFilter filter) {
        BnpUser user = bnpUserService.getById(filter.getUserId());
        System.out.println("sysid" + user.getSysId());
        System.out.println("phone=" + user.getPhone());
        filter.setPhone(user.getPhone());
        List<net.huashitong.user.entity.Message> list = messageService.getMessageInfo(filter);
        System.out.println("list=" + list.size());
        List<MessageFilter> listFilter = new ArrayList<MessageFilter>();
        for (net.huashitong.user.entity.Message m : list) {
            MessageFilter mf = new MessageFilter();
            NodeNewschedules node = nodeNewschedulesService.getById(m.getNodeId());
            mf.setProjectName(m.getProjectName());
            mf.setNodeId(node.getNodeId());
            mf.setStr(node.getNodeName());
            mf.setBegin(node.getPlanBeginDate());
            if (node.getPlanBeginDate() != null && !"".equals(node.getPlanBeginDate()) && node.getPlanTime() != null && !"".equals(node.getPlanTime())) {
                String zxz = DateUtil.addDays(node.getPlanBeginDate(), Integer.parseInt(node.getPlanTime()) - 1);
                System.out.println(zxz);
                mf.setEnd(zxz);
            }
            NewProjectsFilter projectFilter = new NewProjectsFilter();
            projectFilter.setName(m.getProjectName());
            List<NewProjects> listProject = projectService.getProjectInfo(projectFilter);
            if (listProject.size() != 0) {
                mf.setProjectId(listProject.get(0).getSysId());
            }
            mf.setText(m.getText());
            listFilter.add(mf);

        }

        return coverMessage("200", "获取成功", listFilter);
    }

}
